from apps.common.base.views import *
from apps.pay.order.sceneHandle import payReturnScene
from apps.user.dao import UserDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.pay.order.dao import OrderDao
from datetime import timedelta
from apps.merchant.item.dao import ItemDao


class IncomePayViewSet(BaseViewSet):

    '''发起积分支付'''
    @action(methods=['post'], detail=False)
    def sendIncomsPay(self, request):
        params = getRequestParams(request)
        _payway = params.get('payway')
        if isEmptyStr(_payway):
            return Response(response_message('参数payway必填'))
        _order = OrderDao().findOneByOrderId(params.get("orderId"))
        if _order.orderStatus != 'WAIT_PAY':
            return Response(response_modalMessage('待支付的订单才允许支付'))
        
        
        # 扣除积分并创建记录
        realUser = None
        if _order.anotherUser:
            if request.user.id == _order.anotherUser.id:
                realUser = _order.anotherUser
            else:
                return Response(response_modalMessage('您无权操作此订单'))
        else:
            if request.user.id == _order.user.id:
                realUser = _order.user
            else:
                return Response(response_modalMessage('您无权操作此订单'))
            
        # 检查检查一个人只能下一单，如果当前在当天的15点之前，判断如果用户的limitedTimeKillTime在前一天15点到当天15点之间，如果在，则不允许下单
        content = json.loads(_order.content)
        if content.get('orderItemList') and len(content.get('orderItemList'))>0:
            for orderItem in content.get('orderItemList'):
                item = ItemDao().findOneByObjId(orderItem.get('item'))
                if item and item.tags.filter(key__contains='特价秒杀').exists():
                    if _order.user.limitedTimeKillTime:
                        if datetime.datetime.now().hour < 15:
                            if _order.user.limitedTimeKillTime > (datetime.datetime.now().replace(hour=15, minute=0, second=0, microsecond=0) - timedelta(days=1)) and _order.user.limitedTimeKillTime < datetime.datetime.now():
                                return Response(response_message('您已经参与过本期特价秒杀活动'))
                        else:
                            if _order.user.limitedTimeKillTime > (datetime.datetime.now().replace(hour=15, minute=0, second=0, microsecond=0)) and _order.user.limitedTimeKillTime < datetime.datetime.now():
                                return Response(response_message('您已经参与过本期特价秒杀活动'))
    
        # 校验
        _realPay = _order.realPay
        if _payway == 'balance':
            if realUser.balance < _realPay:
                return Response(response_modalMessage('现金余额不足，请使用其他方式支付'))
        elif _payway == 'incomes':
            if realUser.incomes < _realPay:
                return Response(response_modalMessage('消费积分余额不足，请使用其他方式支付'))

        UserDao().subWallet(_payway, realUser, _realPay)
        data = {
            'scene': 'expense',
            'user': realUser.id,
            'fromUser': realUser.id,
            'orderId': _order.orderId,
            'money': _realPay,
            'payway': _payway,
            'changeWay': 'sub',
            'orderStatus': 'FINISH'
        }
        RecordIncomesDao().create(data)

        payReturnScene(_payway, _order.orderId, '','','')
        return Response(response_success('支付成功'))